<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="550"
    >
      <el-table-column label="角色" sortable="custom" align="center" width="180">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色描述" width="420" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="jump(`/rbac/role_user?role=${row.name}`)">用户</el-button>
          <el-button type="primary" size="mini" @click="editPermission(row)">权限</el-button>
          <el-button type="primary" size="mini" @click="editMenu(row)">菜单</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建 -->
    <el-dialog class="data-form-dialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item
          label="角色名称"
          prop="name"
          :rules="[
            { required: true, message: '请填写角色名称'},
            { type: 'string', message: '角色名称必需是字符串'},
            { min: 2, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.name" :disabled="dialogStatus==='update'" placeholder="角色名称必需为英文" />
        </el-form-item>
        <el-form-item
          v-if="dialogStatus==='update'"
          label="新角色名称"
          prop="new_name"
          :rules="[
            { required: true, message: '请填写角色名称'},
            { type: 'string', message: '角色名称必需是字符串'},
            { min: 2, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.new_name" placeholder="角色名称必需为英文" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="description"
          :rules="[
            { required: true, message: '请填写角色描述'},
            { min: 2, max: 128, message: '长度2-128'}
          ]"
        >
          <el-input v-model="temp.description" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submiting" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog class="assign-form-dialog" title="权限" :visible.sync="assignDiadlogShow">
      <el-transfer
        v-model="assignData"
        :props="{
          key: 'name',
          label: 'description'
        }"
        filterable
        :titles="['权限', '已授权']"
        :button-texts="['到左边', '到右边']"
        :data="permissionData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDiadlogShow = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submiting" @click="assign()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog class="assign-form-dialog" title="菜单" :visible.sync="menuDiadlogShow">
      <el-tree
        ref="menuRef"
        :data="menuData"
        :show-checkbox="true"
        node-key="id"
        :default-checked-keys="currentRole.menus"
        :props="{
          children: 'children',
          label: 'name'
        }"
      />
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button @click="clearMenu()">
            清空
          </el-button>

          <el-button @click="checkedAllMenu()">
            全选
          </el-button>
        </div>
        <div>
          <el-button @click="menuDiadlogShow = false">
            取消
          </el-button>
          <el-button type="primary" :loading="submiting" @click="menu()">
            保存
          </el-button>
        </div>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  fetchRoleList,
  fetchCreateRole,
  fetchDeleteRole,
  fetchAssignPermission,
  fetchUpdateRole,
  fetchAssignMenu
} from '@/api/role'

import {
  fetchPermissionList
} from '@/api/permission.js'

import {
  fetchMenuList
} from '@/api/menu.js'

export default {
  name: 'Role',
  components: {},
  data() {
    return {
      tableKey: 0,
      list: [],
      roleData: {},
      assignData: [],
      permissionData: [],
      menuData: [],
      total: 0,
      assignDiadlogShow: false,
      dialogFormVisible: false,
      menuDiadlogShow: false,
      dialogStatus: '',
      listLoading: true,
      submiting: false, // 提交中
      listQuery: {},
      temp: {
        name: '',
        new_name: '',
        description: ''
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {},
      ruleProps: {
        label: 'name'
      },
      currentRole: {}
    }
  },
  created() {
    this.getList()
    this.getPermissionList()
    this.getMenuList()
  },
  methods: {
    clearMenu() {
      this.$refs.menuRef.setCheckedKeys([])
    },
    checkedAllMenu() {
      const arr = []
      for (const i in this.menuData) {
        arr.push(this.menuData[i].id)
      }
      this.$refs.menuRef.setCheckedKeys(arr)
    },
    // 获取权限列表
    getPermissionList() {
      const _this = this
      fetchPermissionList().then(res => {
        _this.permissionData = res.data.items
      })
    },
    // 获取菜单列表
    getMenuList() {
      const _this = this
      fetchMenuList().then(res => {
        _this.menuData = res.data.items
      })
    },
    // 权限
    editPermission(item) {
      this.currentRole = item
      this.assignData = item.permissions
      this.assignDiadlogShow = true
    },
    // 菜单
    editMenu(item) {
      this.currentRole = item
      this.menuDiadlogShow = true
    },
    // 授权
    assign() {
      if (this.submiting) return
      this.submiting = true
      const i = this.list.findIndex(v => v.name === this.currentRole.name)
      if (i == -1) return
      fetchAssignPermission(this.list[i].name, this.assignData).then(res => {
        this.$notify({
          title: 'Success',
          message: '授权成功',
          type: 'success',
          duration: 2000
        })
        this.list[i].permissions = Object.assign([], this.assignData)
        this.submiting = false
      }, () => {
        this.submiting = false
      })
    },
    // 菜单
    menu() {
      if (this.submiting) return
      this.submiting = true
      const i = this.list.findIndex(v => v.name === this.currentRole.name)
      if (i === -1) return
      var menuData = this.$refs.menuRef.getCheckedKeys()

      fetchAssignMenu(this.currentRole.name, menuData).then(res => {
        this.$notify({
          title: 'Success',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
        this.list[i].menus = Object.assign([], menuData)
        this.submiting = false
      }, () => {
        this.submiting = false
      })
    },
    resetTemp() {
      this.temp = {
        name: '',
        new_name: '',
        description: ''
      }
    },
    // 创建
    handleCreate() {
      if (this.dialogStatus === 'update') {
        this.resetTemp()
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.roleData = row
      this.temp = Object.assign({ new_name: '' }, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 提交表单
    createData() {
      this.submiting = true
      this.submitData()
    },
    updateData() {
      this.submiting = true
      this.submintUpdateData()
    },
    submintUpdateData() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchUpdateRole(this.temp).then((res) => {
            _this.roleData.name = _this.temp.new_name
            _this.roleData.description = _this.temp.description
            _this.dialogFormVisible = false
            _this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            _this.submiting = false
          }, _ => {
            _this.submiting = false
          })
        } else {
          _this.submiting = false
        }
      })
    },
    submitData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchCreateRole(this.temp).then((res) => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.resetTemp()
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })

            this.submiting = false
          }, (err) => {
            this.submiting = false
          })
        } else {
          this.submiting = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            fetchDeleteRole(row.name).then((res) => {
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success',
                duration: 3000
              })
              this.list.splice(index, 1)

              instance.confirmButtonLoading = false
              done()
            }, (err) => {
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      })
    },
    getList() {
      fetchRoleList().then(res => {
        this.listLoading = false
        this.list = res.data.items
      }, rej => {
        this.listLoading = false
      })
    },
    jump(url) {
      this.$router.push(url)
    }
  }
}
</script>

<style>
  .assign-form-dialog > .el-dialog {
    width: 750px;
  }

  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .filter-container .filter-item {
    display: inline-block;
    vertical-align: middle;
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
